//
//  DDZdtjVCViewController.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/19.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDZdtjVC.h"
#import "DDNetWorkAPIClient.h"
#import "DDAnswerStat.h"
#import "UIImageView+WebCache.h"
#import "DDProgressView.h"
#import "DDZdtjDetailVC.h"
#import "DDTJ.h"
@interface DDZdtjVC ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSArray *datas;
@property(nonatomic,strong)NSMutableDictionary *tjDatas;
@end

@implementation DDZdtjVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createUI];
    [self createData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    [super viewWillAppear:animated];
}
- (void)createUI
{
    self.view.backgroundColor = RGB(245, 245, 245);
    self.tableView.backgroundColor = RGB(245, 245, 245);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBarHidden = YES;
    //自定义TAB BAR UI
    [self addNavigatorTitle:NSLocalizedString(@"统计结果", nil) parent:self.view];
    self.barViewControl.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"top_Background"]];
    
    [self AddLeftBtnAction:@"" normal:@"top_返回" selected:@"" action:^{
        [self.navigationController popViewControllerAnimated:YES];
        //[self dismissViewControllerAnimated:YES completion:nil];
    }];

    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width,0.1f)];
    
}


-(void)createData
{
    _tjDatas = [NSMutableDictionary dictionary];
    
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
    [network mainAnswerStat:@{@"topicId":_topicId} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        if (isSuccess) {
            DDAnswerStat *stat = object;
            _datas = stat.data;
            [self.tableView reloadData];
        }
    }];
}





- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _datas.count;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int height = 100;
    DDAnswerStatInfo *statinfo = _datas[indexPath.section];
    DDAnswerQuestion *question = statinfo.question;
    NSArray *bodys = question.body;
    if (_showAnswer) {
        height += 50;
    }
//    if (!statinfo.option || statinfo.option.count == 0) {
//        height += 30;
//    }
    if (bodys.count > 0) {
        DDAnswerBody *body = bodys[0];
        if ([body.type isEqualToString:@"IMAGE"]) {
            height += 150;
        }
    }
    
    return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }

    
    
    DDAnswerStatInfo *statinfo = _datas[indexPath.section];
    DDAnswerQuestion *question = statinfo.question;
    NSArray *bodys = question.body;
    if (statinfo) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 30, 32)];
        label.text = [NSString stringWithFormat:@"%ld.",(long)indexPath.section+1];
        [cell.contentView addSubview:label];
        int height = label.frame.size.height + 10;
    if (bodys.count > 0) {
        DDAnswerBody *body = bodys[0];
        
        
        
        if ([body.type isEqualToString:@"TEXT"]) {
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake([self xPostiong:label sp:0], 5, self.tableView.frame.size.width-16, 32)];
            titleLabel.text = body.text;
            [cell.contentView addSubview:titleLabel];
        }else if ([body.type isEqualToString:@"IMAGE"])
        {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake([self xPostiong:label sp:0], 5, self.tableView.frame.size.width-40, 150)];
             [imageView sd_setImageWithURL:[NSURL URLWithString:body.url] placeholderImage:[UIImage imageNamed:@"首页-答疑-客观题-单选习题拍照图-通用"]options:SDWebImageRefreshCached];
            [cell.contentView addSubview:imageView];
            height+=150;
        }
    }
        if (_showAnswer) {
            UILabel *textlabel = [[UILabel alloc] initWithFrame:CGRectMake(15,height,60,24)];
            //正确
//            NSInteger zqtotal = 0;
//            DDAnswerStatResult *result;
            
            
            int answerTotal = [statinfo.answerTotal intValue];//总共多少人回答
            int notAnswerTotal = [statinfo.notAnswerTotal intValue];//未回答多少人
            int zqtotal = 0;//正确多少人
            int errortotal = 0;
            if (statinfo.result.count > 0) {
              DDAnswerStatResult * result = statinfo.result[0];
                zqtotal = [result.total intValue];
                
            }
            if (statinfo.result.count > 1) {
                //错误
              DDAnswerStatResult * result1 = statinfo.result[1];
                errortotal = [result1.total intValue];
            }
            
            //DDAnswerQuestion *question = statinfo.question;
            
            DDProgressView * errorProgressView = [[DDProgressView alloc] initWithFrame:CGRectMake([self xPostiong:textlabel sp:10], height, self.tableView.frame.size.width-100.0f, 0.0f)];
            errorProgressView.hidden = YES;
            [errorProgressView setOuterColor: [UIColor clearColor]] ;
            [errorProgressView setInnerColor: RGB(53, 171, 232)] ;
            [errorProgressView setEmptyColor: [UIColor redColor]] ;
            
            
            
            DDProgressView * progressView2 = [[DDProgressView alloc] initWithFrame: CGRectMake([self xPostiong:textlabel sp:10], height, self.tableView.frame.size.width-100.0f, 0.0f)] ;
            [progressView2 setOuterColor: [UIColor clearColor]] ;
            [progressView2 setInnerColor: RGB(53, 171, 232)] ;
            [progressView2 setEmptyColor: [UIColor lightGrayColor]] ;
            
            
            [cell.contentView addSubview:errorProgressView];
            [cell.contentView addSubview: progressView2] ;
            //if (![@"" isEqualToString:question.answer] || question.answer) {//有正确答案
            if (statinfo.question.answer.length > 0) {

                NSString *text = [NSString stringWithFormat:@"%ld/%ld/%ld",(long)zqtotal,(long)errortotal,(long)[statinfo.notAnswerTotal integerValue]];
                NSArray *arr = [text componentsSeparatedByString:@"/"];
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:text];
                [str addAttribute:NSForegroundColorAttributeName value:RGB(85, 205, 234) range:NSMakeRange(0,((NSString *)arr[0]).length)];
                [str addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(((NSString *)arr[0]).length+1,((NSString *)arr[1]).length)];
                [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(((NSString *)arr[0]).length+((NSString *)arr[1]).length+2,((NSString *)arr[2]).length)];
                
                textlabel.attributedText = str;
                [cell.contentView addSubview:textlabel];
                
                if ((zqtotal +errortotal) == 0) {
                    if (notAnswerTotal > 0) {
                        [errorProgressView setProgress:1.0];
                        progressView2.hidden = YES;
                        errorProgressView.hidden= NO;
                    }else{
                    [progressView2 setProgress:1.0];
                    [progressView2 setInnerColor:[UIColor lightGrayColor]];
                    [errorProgressView setInnerColor: [UIColor lightGrayColor]] ;
                    }
                }else{
                    if (notAnswerTotal == 0 && zqtotal+errortotal!=0) {
                         [progressView2 setProgress:(zqtotal*1.0f)/((zqtotal+errortotal)*1.0f)];
                    }else{
                        [progressView2 setProgress:(zqtotal*1.0f)/((zqtotal+errortotal)*1.0f)];
                        errorProgressView.hidden = NO;
                        double xx = ((zqtotal+errortotal)*1.0)/(notAnswerTotal+zqtotal+errortotal)*1.0;
                        //progressView2 = [[DDProgressView alloc] initWithFrame: CGRectMake([self xPostiong:textlabel sp:10], height, self.tableView.frame.size.width- (self.tableView.frame.size.width*xx), 0.0f)] ;
                        progressView2.frame = CGRectMake(progressView2.frame.origin.x, progressView2.frame.origin.y, progressView2.frame.size.width*xx, progressView2.frame.size.height);
                        
                        NSLog(@"%@",progressView2);
                    }
                   
                }
                
//                else if (zqtotal> 0 && [statinfo.notAnswerTotal intValue] > 0)
//                {
//                    [progressView2 setProgress:errortotal/(errortotal+[statinfo.notAnswerTotal intValue])];
//                    [progressView2 setInnerColor: [UIColor redColor]] ;
//                }
//                else
//                    [progressView2 setProgress:zqtotal/(zqtotal +errortotal)];
                
                
                
                height += 50;

            }else{//没有正确答案
                
                NSString *text = [NSString stringWithFormat:@"%ld/%ld",(long)answerTotal-notAnswerTotal,(long)notAnswerTotal];
                
                NSArray *arr = [text componentsSeparatedByString:@"/"];
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:text];
                [str addAttribute:NSForegroundColorAttributeName value:RGB(85, 205, 234) range:NSMakeRange(0,((NSString *)arr[0]).length)];
                [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(((NSString *)arr[0]).length+1,((NSString *)arr[1]).length)];
                textlabel.attributedText = str;
                [cell.contentView addSubview:textlabel];
                progressView2.hidden = YES;
                errorProgressView.hidden = NO;
               
                if (answerTotal+notAnswerTotal > 0) {
                    NSLog(@"%d",answerTotal+notAnswerTotal);
                    [errorProgressView setProgress:((answerTotal-notAnswerTotal)*1.0f)/(answerTotal*1.0f)];
                }else{
                    [errorProgressView setProgress:0];
                    [errorProgressView setInnerColor: [UIColor redColor]] ;
                }
                height += 50;
                
            }
            
            
//            if (statinfo.result.count > 0) {
//                result = statinfo.result[0];
//                zqtotal = [result.total integerValue];
//                
//            }else{
////                NSString *str =  question.answer;
////                if ([str isEqualToString:@""] && zqtotal == 0 ) {
////                    zqtotal = [statinfo.answerTotal integerValue];
////                }
//            }
//            NSInteger errortotal = 0;
//            DDAnswerStatResult *result1;
//            if (statinfo.result.count > 1) {
//                //错误
//                result1 = statinfo.result[1];
//                errortotal = [result1.total integerValue];
//            }
            
//           NSString *text = [NSString stringWithFormat:@"%ld/%ld/%ld",(long)zqtotal,(long)errortotal,(long)[statinfo.notAnswerTotal integerValue]];
//            NSArray *arr = [text componentsSeparatedByString:@"/"];
//            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:text];
//            [str addAttribute:NSForegroundColorAttributeName value:RGB(85, 205, 234) range:NSMakeRange(0,((NSString *)arr[0]).length)];
//            [str addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(((NSString *)arr[0]).length+1,((NSString *)arr[1]).length)];
//            [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(((NSString *)arr[0]).length+((NSString *)arr[1]).length+2,((NSString *)arr[2]).length)];
//            
//            textlabel.attributedText = str;
//            
//             [cell.contentView addSubview:textlabel];
            
//            DDProgressView * progressView2 = [[DDProgressView alloc] initWithFrame: CGRectMake([self xPostiong:textlabel sp:10], height, self.tableView.frame.size.width-100.0f, 0.0f)] ;
//            [progressView2 setOuterColor: [UIColor clearColor]] ;
//            [progressView2 setInnerColor: RGB(53, 171, 232)] ;
//            [progressView2 setEmptyColor: [UIColor lightGrayColor]] ;
//            if ((zqtotal +errortotal) == 0) {
//                [progressView2 setProgress:1.0];
//                [progressView2 setInnerColor: [UIColor redColor]] ;
//            }
//            else if (zqtotal> 0 && [statinfo.notAnswerTotal intValue] > 0)
//            {
//                [progressView2 setProgress:errortotal/(errortotal+[statinfo.notAnswerTotal intValue])];
//                [progressView2 setInnerColor: [UIColor redColor]] ;
//            }
//            else
//            [progressView2 setProgress:zqtotal/(zqtotal +errortotal)];
//            [cell.contentView addSubview: progressView2] ;
//    
//            height += 50;
            
        }
        
        
        NSArray *options = statinfo.option;
        
        for (int i = 0; i < options.count; i++) {
            DDAnswerStatOption *option = options[i];
            
            UIButton *buttion = [UIButton buttonWithType:UIButtonTypeCustom];
            
            buttion.frame = CGRectMake((self.tableView.frame.size.width/options.count)*i + 10,height,90,44);
            [buttion setTitle:[NSString stringWithFormat:@"%@ %@人",option.title,option.total] forState:UIControlStateNormal];
            [buttion setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [buttion setTitleColor:RGB(53, 171, 232) forState:UIControlStateSelected];
            buttion.tag = 100+i+(indexPath.section*10);
            //if ([option.total integerValue] > 0 && _showAnswer) {
            if ([option.total integerValue] > 0) {

                [buttion addTarget:self action:@selector(optionSelect:) forControlEvents:UIControlEventTouchUpInside];
            }
            //textlabel.text = [NSString stringWithFormat:@"%@ %@人",option.title,option.total];
            
            if (_showAnswer && [statinfo.question.answer isEqualToString:option.title]) {
               // textlabel.textColor = RGB(53, 171, 232);
                buttion.selected = YES;
            }
            [cell.contentView addSubview:buttion];
        }
        if (!statinfo.option || statinfo.option.count == 0) {
            UILabel *textlabel = [[UILabel alloc] initWithFrame:CGRectMake(10,height,150,32)];
            textlabel.text = [NSString stringWithFormat:@"答题人数:%@",statinfo.answerTotal];
            [cell.contentView addSubview:textlabel];
        }
        
    }
   
    
    
    
    
    return cell;
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DDAnswerStatInfo *statinfo = _datas[indexPath.section];
    DDAnswerQuestion *question = statinfo.question;
    
    [self subdata:@"0" topicID:_topicId qid:question.id statinfo:statinfo question:question];
    
    
    
}

- (void)subdata:(NSString *)result topicID:(NSString *)topicID qid:(NSString *)qid statinfo:(DDAnswerStatInfo *)statinfo question:(DDAnswerQuestion *)question
{
    if ([result integerValue] > 3) {
        
        [self process:statinfo question:question topicID:topicID qid:qid];
        return;
    }
    __weak DDZdtjVC *weakSelf = self;
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network mainAnswerUser:@{@"topicId":topicID,@"qid":qid,@"result":result} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        NSLog(@"%@",object);
        if (object) {
            DDTJ *tj = (DDTJ *)object;
            [weakSelf.tjDatas setObject:tj.data forKey:result];
            [weakSelf subdata:[NSString stringWithFormat:@"%d",[result integerValue]+1] topicID:topicID qid:qid statinfo:statinfo question:question];
            
            
        }
    }];
    
}
- (void)process:(DDAnswerStatInfo *)statinfo question:(DDAnswerQuestion *)question topicID:(NSString *)topicID qid:(NSString *)qid
{
    if (_showAnswer) {
        NSLog(@"%@",_tjDatas);
        DDZdtjDetailVC *detailVC = [[DDZdtjDetailVC alloc] initWithNibName:@"DDZdtjDetailVC" bundle:nil];
        // DDAnswerStatInfo *statinfo1 = statinfo;
        //DDAnswerQuestion *question2 = question;
        detailVC.navigationController.navigationBarHidden = NO;
        detailVC.topicId = _topicId;
        detailVC.qid = question.id;
        detailVC.datas = _tjDatas;
        if (statinfo.question.answer.length > 0) {
            detailVC.isHasAnswer = YES;
        }else{
            detailVC.isHasAnswer = NO;
        }
        
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}




-(float) xPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.width+view.frame.origin.x + sp;
}

-(float) yPostiong:(UIView *)view sp:(float)sp
{
    return view.frame.size.height+view.frame.origin.y + sp;
}


-(void)optionSelect:(UIButton *)sender
{
    NSInteger tag = sender.tag;
    NSArray *array = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
    NSString *result = array[tag % 10];
    NSInteger section = (tag-100)/10;
    
    DDAnswerStatInfo *statinfo = _datas[section];
    DDAnswerQuestion *question = statinfo.question;
    
    __weak DDZdtjVC *weakSelf = self;
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc] init];
    [network mainAnswerUser:@{@"topicId":_topicId,@"qid":question.id,@"answer":result} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        NSLog(@"%@",object);
        if (object) {
            DDTJ *tj = (DDTJ *)object;
            
            NSMutableDictionary * data = [NSMutableDictionary dictionary];
            if (tj) {
                [data setValue:tj.data forKey:@"选项"];
            }
            
            
            DDZdtjDetailVC *detailVC = [[DDZdtjDetailVC alloc] initWithNibName:@"DDZdtjDetailVC" bundle:nil];
            // DDAnswerStatInfo *statinfo1 = statinfo;
            //DDAnswerQuestion *question2 = question;
            detailVC.navigationController.navigationBarHidden = NO;
            detailVC.topicId = _topicId;
            detailVC.qid = question.id;
            detailVC.datas = data;
            detailVC.title = result;
                // detailVC.optionResult = result;
            if (statinfo.question.answer.length > 0) {
                detailVC.isHasAnswer = YES;
            }else{
                detailVC.isHasAnswer = NO;
            }
            
            [weakSelf.navigationController pushViewController:detailVC animated:YES];
        }
    }];
    
}
@end
